<template>
  <div class="app-container">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams">
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="变更类型">
              <el-select v-model="queryParams.changeType" placeholder="请选择变更类型" clearable>
                <el-option v-for="item in changeTypeOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="变更状态">
              <el-select v-model="queryParams.status" placeholder="请选择变更状态" clearable>
                <el-option v-for="item in statusOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="设备名称">
              <el-select v-model="queryParams.deviceName" placeholder="请选择设备名称" clearable filterable style="width: 100%">
                <el-option v-for="item in deviceList" :key="item.equipmentId" :label="item.equipmentName" 
                  :value="item.equipmentName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="变更时间">
              <el-date-picker v-model="queryParams.timeRange" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="4" style="text-align: left;">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="mt-1">
      <el-button type="primary" @click="handleAdd">
        <el-icon>
          <Plus />
        </el-icon>
        新增变更
      </el-button>
      <el-table :data="changeList" border v-loading="loading" @selection-change="handleSelectionChange" class="mt-2">
        <el-table-column type="selection" align="center" />
        <el-table-column prop="changeNumber" label="变更编号" align="center" />
        <el-table-column prop="changeTime" label="变更时间" align="center" />
        <el-table-column prop="changeType" label="变更类型" align="center">
          <template #default="{ row }">
            <el-tag>{{ getDictLabel(changeTypeOptions, row.changeType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="变更状态" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getDictLabel(statusOptions, row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="deviceName" label="设备名称" align="center" />
        <el-table-column prop="deviceModel" label="设备型号" align="center" />
        <el-table-column prop="quantity" label="设备数量" align="center" />
        <el-table-column prop="operator" label="操作人" align="center" />
        <el-table-column prop="createdAt" label="创建时间" align="center" />
        <el-table-column label="操作" align="center" width="220">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(row)" v-if="row.status === 0">
              编辑
            </el-button>
            <el-button size="small" type="success" @click="handleApprove(row)" v-if="row.status === 0">
              通过
            </el-button>
            <el-button size="small" type="danger" @click="handleReject(row)" v-if="row.status === 0">
              拒绝
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)" v-if="row.status === 0">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination class="mt-2" background layout="total, sizes, prev, pager, next, jumper" :total="total"
        v-model:page-size="queryParams.pageSize" v-model:current-page="queryParams.pageNum"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="变更时间" prop="changeTime">
          <el-date-picker v-model="form.changeTime" type="date" placeholder="选择变更时间"
            value-format="YYYY-MM-DD" style="width: 100%" />
        </el-form-item>
        <el-form-item label="变更类型" prop="changeType">
          <el-select v-model="form.changeType" placeholder="请选择变更类型" style="width: 100%">
            <el-option v-for="item in changeTypeOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="+item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-select 
            v-model="form.deviceName" 
            placeholder="请选择设备名称" 
            style="width: 100%" 
            filterable
            @change="handleDeviceChange"
          >
            <el-option 
              v-for="item in deviceList" 
              :key="item.equipmentId" 
              :label="item.equipmentName" 
              :value="item.equipmentName" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备型号" prop="deviceModel" v-if="form.deviceName">
          <el-input v-model="form.deviceModel" placeholder="请输入设备型号" />
        </el-form-item>
        <el-form-item label="设备数量" prop="quantity">
          <el-input-number v-model="form.quantity" :min="1" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="变更原因" prop="reason">
          <el-input v-model="form.reason" type="textarea" :rows="3" placeholder="请输入变更原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialog.visible" :title="`变更记录详情 - ${detailDialog.data.changeNumber}`" width="800px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="变更编号">{{ detailDialog.data.changeNumber }}</el-descriptions-item>
        <el-descriptions-item label="变更时间">{{ detailDialog.data.changeTime }}</el-descriptions-item>
        <el-descriptions-item label="变更类型">
          <el-tag>{{ getDictLabel(changeTypeOptions, detailDialog.data.changeType) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="变更状态">
          <el-tag :type="getStatusTagType(detailDialog.data.status)">
            {{ getDictLabel(statusOptions, detailDialog.data.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="设备名称">{{ detailDialog.data.deviceName }}</el-descriptions-item>
        <el-descriptions-item label="设备型号">{{ detailDialog.data.deviceModel }}</el-descriptions-item>
        <el-descriptions-item label="设备数量">{{ detailDialog.data.quantity }}</el-descriptions-item>
        <el-descriptions-item label="操作人">{{ detailDialog.data.operator }}</el-descriptions-item>
        <el-descriptions-item label="变更原因">{{ detailDialog.data.reason }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailDialog.data.createdAt }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailDialog.data.updatedAt }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getChangeTypeList,
  getStatusList,
  listDeviceChange,
  getDeviceChangeDetail,
  addDeviceChange,
  updateDeviceChange,
  deleteDeviceChange,
  auditDeviceChange
} from '@/api/prod_operate/device/dev_change'

// 导入设备管理列表接口
import { listDeviceManageCopy } from '@/api/prod_operate/device/dev_change'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  changeType: undefined,
  status: undefined,
  deviceName: '',
  timeRange: [],
  startTime: undefined,
  endTime: undefined
})

// 表单数据
const form = reactive({
  id: undefined,
  changeNumber: '',
  changeTime: '',
  changeType: undefined,
  deviceName: '',
  deviceModel: '',
  quantity: 1,
  reason: ''
})

// 对话框控制
const dialog = reactive({
  visible: false,
  title: ''
})

const detailDialog = reactive({
  visible: false,
  data: {}
})

// 下拉选项数据
const changeTypeOptions = ref([])
const statusOptions = ref([])
const deviceList = ref([]) // 设备列表数据

// 表格数据
const changeList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref([])
const formRef = ref()

// 表单验证规则
const rules = reactive({
  changeTime: [
    { required: true, message: '请选择变更时间', trigger: 'change' }
  ],
  changeType: [
    { required: true, message: '请选择变更类型', trigger: 'change' }
  ],
  deviceName: [
    { required: true, message: '请输入设备名称', trigger: 'blur' }
  ],
  deviceModel: [
    { required: true, message: '请输入设备型号', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入设备数量', trigger: 'blur' }
  ],
  reason: [
    { required: true, message: '请输入变更原因', trigger: 'blur' }
  ]
})

// 获取状态标签类型
const getStatusTagType = (status) => {
  const map = {
    0: 'warning', // 待审核
    1: 'success', // 已通过
    2: 'danger'   // 已拒绝
  }
  return map[status] || 'info'
}

// 获取字典标签
const getDictLabel = (options, value) => {
  const item = options.find(item => item.dictValue == value)
  return item ? item.dictLabel : ''
}

// 获取设备管理列表
const fetchDeviceList = async () => {
  try {
    const res = await listDeviceManageCopy({
      pageNum: 1,
      pageSize: 1000 // 获取所有设备数据
    })
    deviceList.value = res.rows || []
  } catch (error) {
    console.error('获取设备列表失败:', error)
    ElMessage.error('获取设备列表失败')
  }
}

// 获取下拉选项数据
const fetchDropdownOptions = async () => {
  try {
    const [changeTypeRes, statusRes] = await Promise.all([
      getChangeTypeList(),
      getStatusList()
    ])
    changeTypeOptions.value = changeTypeRes.data || []
    statusOptions.value = statusRes.data || []
  } catch (error) {
    console.error('获取下拉选项失败:', error)
    ElMessage.error('获取下拉选项失败')
  }
}

// 获取变更记录列表
const fetchChangeList = async () => {
  try {
    loading.value = true

    // 处理时间范围参数
    if (queryParams.timeRange && queryParams.timeRange.length === 2) {
      queryParams.startTime = queryParams.timeRange[0]
      queryParams.endTime = queryParams.timeRange[1]
    } else {
      queryParams.startTime = undefined
      queryParams.endTime = undefined
    }

    const res = await listDeviceChange(queryParams)
    changeList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取变更记录列表失败:', error)
    ElMessage.error('获取变更记录列表失败')
  } finally {
    loading.value = false
  }
}

// 设备选择变化处理
const handleDeviceChange = (deviceName) => {
  // 如果选择了设备，可以自动填充设备型号（可选功能）
  if (deviceName) {
    const selectedDevice = deviceList.value.find(device => device.equipmentName === deviceName)
    if (selectedDevice && selectedDevice.model) {
      form.deviceModel = selectedDevice.model
    }
  }
}

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchChangeList()
}

// 重置查询
const resetQuery = () => {
  queryParams.pageNum = 1
  queryParams.changeType = undefined
  queryParams.status = undefined
  queryParams.deviceName = ''
  queryParams.timeRange = []
  queryParams.startTime = undefined
  queryParams.endTime = undefined
  fetchChangeList()
}

// 分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  fetchChangeList()
}

// 当前页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  fetchChangeList()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新增按钮
const handleAdd = () => {
  dialog.visible = true
  dialog.title = '新增变更记录'

  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields()
  }

  Object.assign(form, {
    id: undefined,
    changeNumber: '',
    changeTime: '',
    changeType: undefined,
    deviceName: '',
    deviceModel: '',
    quantity: 1,
    reason: ''
  })
}

// 编辑按钮
const handleEdit = async (row) => {
  try {
    const res = await getDeviceChangeDetail(row.id)
    Object.assign(form, {
      id: res.data.id,
      changeNumber: res.data.changeNumber,
      changeTime: res.data.changeTime,
      changeType: res.data.changeType,
      deviceName: res.data.deviceName,
      deviceModel: res.data.deviceModel,
      quantity: res.data.quantity,
      reason: res.data.reason
    })

    dialog.visible = true
    dialog.title = '编辑变更记录'
  } catch (error) {
    console.error('获取变更记录详情失败:', error)
    ElMessage.error('获取变更记录详情失败')
  }
}

// 查看详情
const handleView = async (row) => {
  try {
    const res = await getDeviceChangeDetail(row.id)
    detailDialog.data = res.data
    detailDialog.visible = true
  } catch (error) {
    console.error('获取变更记录详情失败:', error)
    ElMessage.error('获取变更记录详情失败')
  }
}

// 通过审批
const handleApprove = (row) => {
  ElMessageBox.confirm(`确认通过变更记录 "${row.changeNumber}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return auditDeviceChange({ id: row.id, status: 1 })
  }).then(() => {
    ElMessage.success('操作成功')
    fetchChangeList()
  }).catch(() => { })
}

// 拒绝审批
const handleReject = (row) => {
  ElMessageBox.confirm(`确认拒绝变更记录 "${row.changeNumber}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return auditDeviceChange({ id: row.id, status: 2 })
  }).then(() => {
    ElMessage.success('操作成功')
    fetchChangeList()
  }).catch(() => { })
}

// 删除按钮
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除变更记录 "${row.changeNumber}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return deleteDeviceChange(row.id)
  }).then(() => {
    ElMessage.success('删除成功')
    fetchChangeList()
  }).catch(() => { })
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    if (form.id) {
      await updateDeviceChange(form)
    } else {
      await addDeviceChange(form)
    }

    ElMessage.success('操作成功')
    dialog.visible = false
    fetchChangeList()
  } catch (error) {
    console.error('保存变更记录失败:', error)
  }
}

// 初始化加载数据
onMounted(() => {
  fetchDropdownOptions()
  fetchDeviceList() // 加载设备列表
  fetchChangeList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.mt-1 {
  margin-top: 20px;
}

.mt-2 {
  margin-top: 20px;
}

.pre-formatted {
  white-space: pre-wrap;
  word-wrap: break-word;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}
</style>